﻿
var jqGridHelper = {
    /** 常用配置 */
    getConfig: function (pageId, c) {
        ///    <summary>
        ///    返回jqGrid的通用配置项
        ///    <summary>
        ///    <returns type="Object" />
        ///	<param name="divPageId" type="String">
        ///		Grid的分页divID，含"#"
        ///	</param>
        ///	<param name="h" type="Number">
        ///		Grid的高
        ///	</param>
        ///	<param name="c" type="Object">
        ///		Grid的非通用配置项
        ///	</param>
        //分页设置
        var config = {
            datatype: "json",
            mtype: "post",
            pager: pageId,
            sortable: true, //交换列，如果启用，则不能使用冻结列功能。
            loadonce: false,
            rownumbers: true,
            rownumWidth: 35,
            gridview: true,
            viewrecords: true,
            sortorder: "asc",
            shrinkToFit: false,
            multiselect: false,
            multiselectWidth: 35,
            altRows: true,
            autowidth: true,
            checkbox: false,
            altclass: "jqgrid-row",
            alwaysTriggerAfterSaveCell: true,
            jsonReader: { repeatitems: false },
            loadError: function (xhr, status) {
                var message = "<div style='line-height:30px' >访问数据出错，请与管理员联系！</div>";
                $("#divErrorInfo").html(message);
                $("#divError").dialog({
                    modal: true,
                    height: $(document).height() * 0.4,
                    width: $(document).width() * 0.4
                });
            },
            afterEditCell: function (rowid, cellname, value, iRow, iCol) {
                $.autoSelectCell(rowid, cellname, value);
            }
        }
        return jQuery.extend(config, c);
    },
    getAllRowData: function (gridId) {
        $(gridId).saveEdittingCell();
        var ids = $(gridId).getDataIDs();
        var data = $(gridId).getRowData(ids[0]);
        var dataList = new Array();
        for (i = 0; i < ids.length; i++) {
            data = $(gridId).getRowData(ids[i]);
            dataList[i] = data;
        }
        return dataList;
    },
    //*** 关于自定义编辑框--开始****//

    dateElement: function (value, options) {
        var el = document.createElement("input");
        $(el).attr("type", "text").attr("__type", "date").css("width", "98%").val(value);
        $(el).click(WdatePicker);
        $(el).focus(WdatePicker);
        //$(el).keyup($dp.hide);
        return el;
    },
    dateValue: function (el) {
        return $(el).val();
    },
    checkBoxElement: function (value, option) {
        var el = document.createElement("input")
        $(el).attr("type", "checkbox").attr("name", option.name);
        if (value == '1' || value == "是") {
            $(el).attr("checked", "checked");
        }
        return el;
    },
    checkBoxElementValue: function (e) {
        if ($(e).attr("checked")) {
            return "1";
        }
        else { return "0"; }
    },
    RadioList: function (value, option) {
        var container = document.createElement("span");
        var options = option.value;
        var optionsArray = options.split(';');
        for (var i = 0; i < optionsArray.length; i++) {
            var el = document.createElement("input")
            $(el).attr("type", "radio").attr("name", option.name);
            $(el).val(optionsArray[i].split(':')[0]);

            if (optionsArray[i].split(':')[0] == value) {
                $(el).attr("checked", "checked")
            }
            $(el).appendTo($(container));
            $(container).append(optionsArray[i].split(':')[1]);
            $(container).append("&nbsp;");
        }
        return container;
    },
    RadioListValue: function (e) {
        var val = $(e).find("input[type='radio']:checked").val();
        if (val == undefined) return "";
        return val;
    },
    longTextElement: function (value, options) {
        var spContainer = document.createElement("span");
        $(spContainer).css("position", "relative");
        var spNote = document.createElement("span");
        $(spNote).attr("class", "showtextbtnGrid");
        $(spNote).css({ position: "absolute", right: 0, top: 0 });

        var el = document.createElement("input");

        if (typeof (options.readonly) == "boolean" && options.readonly == true) {
            $(el).attr("readonly", "true");
        }

        $(el).attr("type", "text").val(value).attr("id", "t_" + options.id).css("width", "98%");
        if (typeof (options.autocomplete) != 'undefined') {
            if (typeof (options.autocomplete.source) != 'undefined') {
                $(el).autocomplete({ source: options.autocomplete.source, minLength: 0 });
                $(el).focus(function () {
                    $(el).autocomplete("search");
                })
            }
        }
        $(el).appendTo($(spContainer));
        $(spNote).click(function () {
            $.ShowTextDialog("t_" + options.id);
        })
        $(spNote).appendTo($(spContainer));
        return spContainer;
    },
    longTextValue: function (el) {
        return $(el).find('input').val();
    },
    //字典
    dataElement: function (value, options) {
        var el = document.createElement("input");
        $(el).attr("type", "text").css("width", "100%").val(value).attr("id", options.id);

        var rowId = String(options.id).substring(0, String(options.id).indexOf('_'));
        var inputUrl = "";
        var searshUrl = "";
        var windowsUrl = "";
        var titles = "";

        //右键弹窗
        if (typeof (options.contextDialog) != 'undefined') {
            var wWidth = 650, wHeight = 360, wTitle = '选择';
            if (typeof (options.contextDialog.width) != 'undefined')
                wWidth = options.contextDialog.width;
            if (typeof (options.contextDialog.height) != 'undefined')
                wHeight = options.contextDialog.height;
            if (typeof (options.contextDialog.title) != 'undefined')
                wTitle = options.contextDialog.title;
            var extraParams = { rowId: rowId };
            if (typeof (options.contextDialog.exParams) != 'undefined' && options.contextDialog.exParams != null) {
                $.each(options.contextDialog.exParams, function (key, param) {
                    extraParams[key] = param;
                });
            }
            $(el).bindContextDialog(wTitle, options.contextDialog.url, extraParams,
                options.contextDialog.callBack, wWidth, wHeight);
        }
        //comboGrid
        if (typeof (options.comboGrid) != 'undefined') {
            var _url = options.comboGrid.url;
            var queryStr = $.jsonToQueryString(options.comboGrid.exParams);
            if (queryStr != null) {
                _url += '?' + queryStr;
            }
            $(el).combogrid({
                url: _url,
                showOn: true,
                sidx: options.comboGrid.sortname,
                sord: typeof (options.comboGrid.sortorder) == 'undefined' ? 'asc' : options.comboGrid.sortorder,
                readonly: (typeof (options.readonly) != 'undefined' && (options.readonly || options.readonly == 'true')) ? true : false,
                colModel: options.comboGrid.colModel,
                select: function (event, ui) {
                    /***
                    2012-09-24 段松波增加 
                    options.comboGrid.select is function, example like this:
                    options.comboGrid.select:function(item){ return item.name; }
                    */
                    if (typeof (options.comboGrid.select) == 'function') {
                        $(el).val(options.comboGrid.select(ui.item, rowId));
                    }
                    return false;
                }
            });
        }
        //自动完成
        if (typeof (options.autoComplete) != 'undefined') {
            var extraParams = { rowId: rowId };
            if (typeof (options.autoComplete.exParams) != 'undefined' && options.autoComplete.exParams != null) {
                $.each(options.autoComplete.exParams, function (key, param) {
                    extraParams[key] = param;
                });
            }
            var _config = { source: options.autoComplete.url, exParams: extraParams,
                callBack: options.autoComplete.callBack, checkInput: false,
                delay: options.autoComplete.delay
            };
            $(el).configAutoComplete(_config);
            //$(el).bindAutoComplete(options.autoComplete.url, extraParams, options.autoComplete.callBack, true, true, options.autoComplete.delay);
        }
        if (typeof (options.readonly) != 'undefined' && (options.readonly || options.readonly == 'true')) {
            $(el).attr("readonly", "readonly");
        }
        return el;
    },
    dataValue: function (el) {
        var val = $(el).val();
        if (val == undefined)
            return "";
        return val;
    },
    validateRowNums: function (gridId, rowid) {
        $(gridId).saveEdittingCell();
        var rowNum = $(gridId).getGridParam('rowNum');
        if (rowid > rowNum) {
            $(gridId).delRowData(rowid);
            alert('警告！当前单据最多允许录入 ' + rowNum + ' 条明细');
        }
    },
    //添加导出按钮
    addExportButton: function (config) {
        var _defConfig = { gridId: '#tableId', pagerId: '#pageId', id: 'grid_btn_export', caption: '导出', formId: '#queryForm', async: true };
        config = $.extend(_defConfig, config);
        $(config.gridId).navGrid(config.pagerId, { add: false, edit: false, del: false, search: false, refresh: false
        }).navButtonAdd(config.pagerId, { id: config.id, buttonicon: 'ui-icon-folder-open', title: '导出到Excel', caption: config.caption, onClickButton: function () {
            var _sortname = $(config.gridId).getGridParam('sortname');
            var _sortorder = $(config.gridId).getGridParam('sortorder');
            if ($.trim(_sortorder).length == 0) _sortorder = "asc";
            if (config.async) {
                var params = { queryData: $(config.formId).snFormSerialize(), sidx: _sortname, sord: _sortorder }
                jqGridHelper.exportToExcelAsync(config.gridId, params);
            }
            else {
                jqGridHelper.exportToExcel(config.gridId, config.formId);
            }
        }
        });
    },
    //用post的方式同步导出  如果数据行多或者查询结果返回速度慢的情况 用户响应性不好
    //目前未实现按Jqgrid的排序字段排序
    exportToExcel: function (gridId, formId) {
        var _url = $(gridId).getGridParam('url');
        if ($.trim(_url).length == 0) return;
        var _sortname = $(gridId).getGridParam('sortname');
        var _sortorder = $(gridId).getGridParam('sortorder');
        if ($.trim(_sortorder).length == 0) _sortorder = "asc";
        var pageParas = "sidx=" + _sortname + "&sord=" + _sortorder;
        if (_url.indexOf('?') >= 0) {
            _url += "&" + pageParas;
        }
        else {
            _url += "?" + pageParas;
        }
        $(formId).attr("action", _url);
        var q = document.createElement("input");
        alert(_url);
        alert($(formId).serialize());
        $(q).attr("name", "queryData").attr("type", "hidden").val($(formId).serialize());
        $(q).appendTo(formId);
        var _colModel = $(gridId).getGridParam('colModel');
        _colModel = JSON.stringify(_colModel);
        var c = document.createElement("input");
        $(c).attr("name", "colModel").attr("type", "hidden").val(_colModel);
        $(c).appendTo(formId);
        $(formId).trigger("submit");
        $(formId).attr("action", "#");
        $(q).remove(); $(c).remove();
    },
    //用Ajax异步方式导出，由于使用异步，可以附加等待界面，提高了响应性，但需要一个单独下载文件的而面  且IE需要设置取消拦截下载
    exportToExcelAsync: function (gridId, queryPara) {
        var _colModel = $(gridId).getGridParam('colModel');
        _colModel = JSON.stringify(_colModel);
        var para = { colModel: _colModel };
        para = $.extend(para, queryPara);
        var _url = $(gridId).getGridParam('url');
        if ($.trim(_url).length == 0) return;
        lockUI();
        $.post(_url, para, function (data) {
            unLockUI();
            if (data.Success) {
                window.location.href = '/Home/DownLoadExcel/?fileName=' + encodeURIComponent(data.Data)
            }
            else {
                alert(data.ErrorMessage);
            }
        });
    },
    scrollLeftBottom: function (gridId) {
        $("#gview_" + gridId.replace('#', '') + " .ui-jqgrid-bdiv").scrollLeft(-9999);
        $("#gview_" + gridId.replace('#', '') + " .ui-jqgrid-bdiv").scrollTop(9999);
    },
    delSelRows: function (gridId) {
        $(gridId).saveEdittingCell();
        var ids = String($(gridId).getGridParam("selarrrow")).split(',');
        for (i = ids.length - 1; i >= 0; i--) {
            $(gridId).delRowData(ids[i]); //删除选中的行
        }
    },
    validateMateriel: function (value, colname) {//value 新型号
        var returnData = null;
        $.getJSONSync('/JCZD/WLZD/ValidateMateriel/?id=' + encodeURIComponent(value), null, function (b) {
            if (b)
                returnData = [true, ""];
            else
                returnData = [false, "物料输入不正确！"];
        });
        return returnData;
    },
    serverCellValidate: function (url, para, errmsg) { //自定义验证单元格编辑
        var returnData = null;
        $.ajax({
            type: "GET",
            url: url,
            data: para,
            cache: false,
            dataType: 'json',
            async: false,
            success: function (b) {
                if (b)
                    returnData = [true, ""];
                else
                    returnData = [false, errmsg];
            },
            error: function (httpRequest, errMsg) {
                returnData = [false, "服务器出现错误！"];
            }
        });
        return returnData;
    },
    //获取选中行id（单选模式）
    getSelrow: function (gridId) {
        return $(gridId).jqGrid("getGridParam", "selrow");
    },
    //获取选中行id（复选模式）
    getSelarrrow: function (gridId) {
        return $(gridId).jqGrid('getGridParam', 'selarrrow');
    },
    getAllRowsData: function (gridId) {
        var ids = $(gridId).getDataIDs();
        var data = "";
        var dataList = new Array();
        for (i = 0; i < ids.length; i++) {
            data = $(gridId).getRowData(ids[i]);
            dataList[i] = data;
        }
        return dataList;
    },
    //获取选中行的数据，单行模式
    getSelRowData: function (gridId, cellName) {
        var selectedId = $(gridId).jqGrid("getGridParam", "selrow");
        if (selectedId != null && typeof (selectedId) != undefined) {
            if (selectedId.length > 0) {
                if (typeof (cellName) != 'undefined')
                    return $(gridId).getCell(selectedId, cellName);
                else
                    return $(gridId).getRowData(selectedId);
            }
        }
        return null;
    },
    bindFieldPermission: function (config, option) {
        if (typeof (option) != 'object') return;
        var _tableName = '', _fieldName = option.colName;
        for (var i = 0; i < config.colModel.length; i++) {
            if (config.colModel[i].name == option.colName) {
                _fieldName = option.colName;
                if (typeof (option.tableName) != 'undefined') {
                    _tableName = option.tableName;
                }
                $.ajax({
                    type: "POST",
                    url: '/SNPermissionExt/GetUserDenyFieldType',
                    data: { tableName: _tableName, fieldName: _fieldName },
                    cache: false,
                    dataType: 'json',
                    async: false,
                    success: function (_data) {
                        if (_data == 1) {//拒绝查看
                            config.colModel[i].hidden = true;
                        }
                        else if (_data == 2) {//拒绝编辑
                            $(gridId).setColProp(_fieldName, { editable: false });
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {

                    }
                });
            }
        }
    },
    getColIndex: function (gridId, colName) {
        var colModels = $(gridId).getGridParam('colModel');
        for (var i = 0; i < colModels.length; i++) {
            if (colModels[i].name == colName) {
                return i;
            }
        }
        return 0;
    },
    setToolBarData: function (gridId, dataStr) {
        var toolbarId = "#t_" + gridId.toString().substring(1);
        $(toolbarId).html("");
        $("<div style='margin-top:5px;margin-left:10px'>" + dataStr + "</div>").prependTo($(toolbarId));
    },
    removeHeaderCheckBox: function (gridId) {
        $("#jqgh_" + gridId.toString().substring(1) + "_cb").find("input[type='checkbox']").remove();
    },
    setSelection: function (gridId, func, onselectrow) { //根据条件选择行， func是个函数,参数是行数据  ，返回bool值，如果返回true，则选择行
        var ids = $(gridId).getDataIDs();
        if (typeof (onselectrow) == 'undefined') onselectrow = true;

        if (typeof (func) != 'function') return;
        for (var i = 1; i <= ids.length; i++) {
            var data = $(gridId).getRowData(i);
            if (func(data)) {
                $(gridId).setSelection(i, onselectrow);
            }
        }
    },
    sumCol: function (gridId, colName, sumCheckedRows) {
        var ids = $(gridId).getDataIDs();
        var sumVal = 0;
        if (typeof (sumCheckedRows) == 'boolean' && sumCheckedRows) {
            var multiselect = $(gridId).getGridParam('multiselect');
            if (multiselect) {
                var selectedId = $(gridId).jqGrid('getGridParam', 'selarrrow');
                if (selectedId != null && typeof (selectedId) != 'undefined' && selectedId.length > 0) {
                    $(selectedId.toString().split(',')).each(function (index, rowid) {
                        sumVal += parseFloat($(gridId).getCell(rowid, colName));
                    });
                    return sumVal;
                }
            }
        }
        else {
            for (i = 1; i <= ids.length; i++) {
                sumVal += parseFloat($(gridId).getCell(i, colName));
            }
        }
        return parseFloat(sumVal);
    },
    clearRowData: function (gridId, rowid) {
        var colModels = $(gridId).getGridParam('colModel');
        var isMultiselect = $(gridId).getGridParam('multiselect');
        for (var i = isMultiselect ? 2 : 1; i <= colModels.length; i++) {
            $(gridId).setCell(rowid, i, null);
        }
    },
    setGridFooterData: function (gridId, colName, value) {
        var _gridId = gridId.toString().substring(1);
        $("#gbox_" + _gridId)
            .find("div[class='ui-jqgrid-hbox']")
            .find("td[aria-describedby='" + _gridId + "_" + colName + "']").attr("title", value).text(value);
    },
    refreshUserData: function (gridId, colNames, summaryCol, sumCheckedRows) {
        var _gridId = gridId.toString().substring(1);
        $(colNames).each(function (i, colname) {
            var sumVal = jqGridHelper.sumCol(gridId, colname, sumCheckedRows);
            sumVal = formatMoney(sumVal);
            $("#gbox_" + _gridId)
            .find("table[class='ui-jqgrid-ftable']")
            .find("td[aria-describedby='" + _gridId + "_" + colname + "']").attr("title", sumVal)
            .html(sumVal.indexOf('-') >= 0 ? ('<font color="red">' + sumVal + '</font>') : sumVal);
        });
        if (typeof (summaryCol) != 'undefined') {
            $("#gbox_" + _gridId)
            .find("table[class='ui-jqgrid-ftable']")
            .find("td[aria-describedby='" + _gridId + "_" + summaryCol + "']").attr("title", '合计:').text("合计:");
        }
    },
    setUserData: function (gridId, userdata) {
        var _gridId = gridId.toString().substring(1);
        if (userdata == null) {
            $("#gbox_" + _gridId)
            .find("div[class='ui-jqgrid-hbox']")
            .find("table[class='ui-jqgrid-ftable']")
            .find("td").attr("title", "")
            .html("");
        }
        else {
            $.each(userdata, function (key, param) {
                $("#gbox_" + _gridId)
            .find("div[class='ui-jqgrid-hbox']")
            .find("table[class='ui-jqgrid-ftable']")
            .find("td[aria-describedby='" + _gridId + "_" + key + "']").attr("title", param)
            .html(
            isNaN(param) ? param : parseFloat(param) < 0 ? ('<font color="red">' + formatMoney(param, 2) + '</font>') : formatMoney(param, 2)
            );
            });
        }
    },
    editAllRow: function (gridId) {
        var ids = $(gridId).jqGrid('getDataIDs');
        $(ids).each(function (i, d) {
            $(gridId).jqGrid('editRow', d, true);
        });
        //$(gridId).jqGrid('editRow', ids[0], true);
    },
    //获取选中行的单元格数据（多行模式适用，返回以“,”隔开的字符串)
    getSelRowsData: function (gridId, cellName) {
        var selectedId = $(gridId).jqGrid('getGridParam', 'selarrrow');
        if (selectedId != null && typeof (selectedId) != 'undefined') {
            if (selectedId.length > 0) {
                var array = selectedId.toString().split(',');
                if (typeof (cellName) != 'undefined') {
                    var ids = '';
                    for (var i = 0; i < array.length; i++) {
                        if (array[i].length == 0) continue;
                        ids = ids + $(gridId).getCell(array[i], cellName) + ",";
                    }
                    if (ids.length > 0) {
                        ids = ids.substring(0, ids.length - 1);
                    }
                    return ids;
                }
                else {
                    var dataList = new Array();
                    for (var i = 0; i < array.length; i++) {
                        if (array[i].length == 0) continue;
                        $(gridId).saveRow(array[i], false, 'clientArray');
                        data = $(gridId).getRowData(array[i]);
                        dataList[i] = data;
                    }
                    return dataList;
                }
            }
        }
        return null;
    }
};

function funSaveData(formId, gridId, editUrl) {
    $(gridId).saveEdittingCell();
    var ids = $(gridId).getDataIDs();
    var data = "";
    var dataList = new Array();
    for (i = 0; i < ids.length; i++) {
        data = $(gridId).getRowData(ids[i]);
        dataList[i] = data;
    }
    var postData = {
        detail: $("#" + formId).serialize(),
        dataList: JSON.stringify(dataList)
    };
    $.post(editUrl, postData, function (d) {
        if (d == 1) {
            alert("保存成功！");
        }
        else
            alert("保存失败！提示信息：" + d);
    });
}


//*** 关于自定义Fmatter--开始****//
jQuery.extend($.fn.fmatter, {
    flagImageFmatter: function (cellvalue, options, rowdata) {
        var _yVal;
        if (typeof (options.colModel.editoptions.value) != 'undefined') {
            var optionValue = options.colModel.editoptions.value;
            $(optionValue.split(';')).each(function (i, obj) {
                if (obj.split(':')[0] == 'Y') {
                    _yVal = obj.split(':')[1];
                }
            });
        }
        if (_yVal == '') _yVal = "1";
        if (cellvalue == _yVal) {
            return "<img src='/Content/images/accept.png' width='16' height='16' />";
        }
        return "";
    }
});

jQuery.extend($.fn.fmatter.flagImageFmatter, {
    unformat: function (cellvalue, options) {
        var _yVal, _nVal;
        if (typeof (options.colModel.editoptions.value) != 'undefined') {
            var optionValue = options.colModel.editoptions.value;
            $(optionValue.split(';')).each(function (i, obj) {
                if (obj.split(':')[0] == 'Y') {
                    _yVal = obj.split(':')[1];
                }
                else if (obj.split(':')[0] == 'N') {
                    _nVal = obj.split(':')[1];
                }
            });
        }
        if (_yVal == '') _yVal = "1";
        if (_nVal == '') _nVal = "0";
        if (cellvalue.length > 0) {
            return _yVal
        }
        return _nVal
    }
});

//是否--YN
jQuery.extend($.fn.fmatter, {
    color: function (cellvalue, options, rowdata) {
        var html = '<spand style="background-color:' + cellvalue + ';width:100%;display:-moz-inline-box;display:inline-block;">&nbsp;</span>'
        return html;
    }
});

//jQuery.extend($.fn.fmatter.color, {
//    unformat: function (cellvalue, options) {

//        if (cellvalue != '') {
//            cellvalue = cellvalue.replace('<spand style="background-color:', '').replace(';width:100%;display:-moz-inline-box;display:inline-block;">&nbsp;</span>', '');
//        }
//        return cellvalue;
//    }
//});

//处理标志--KHDZD
jQuery.extend($.fn.fmatter, {
    CLBZmatter: function (cellvalue, options, rowdata) {
        var val = "";
        if (cellvalue == "1" || cellvalue == 1) val = "已处理";
        if (cellvalue == "0" || cellvalue == 0) val = "未处理";
        if (cellvalue == "2" || cellvalue == 2) val = "遗留";
        return val;
    }
});
jQuery.extend($.fn.fmatter.CLBZmatter, {
    unformat: function (cellvalue, options) {
        var val = "";
        if (cellvalue == "已处理") val = "1";
        if (cellvalue == "未处理") val = "0";
        if (cellvalue == "遗留") val = "2";
        return val;
    }
});
//是否--YN
jQuery.extend($.fn.fmatter, {
    YNFmatter: function (cellvalue, options, rowdata) {
        var val = "";
        if (cellvalue == "1" || cellvalue == 1) {
            val = "<img src='/Content/images/tick.png' />"
        }
        if (cellvalue == "0" || cellvalue == 0) {
            val = "<img src='/Content/images/bullet_cross.png' />"
        }
        return val;
    }
});

jQuery.extend($.fn.fmatter.YNFmatter, {
    unformat: function (cellvalue, options) {
        var val = "";
        if (cellvalue == "是") val = "1";
        if (cellvalue == "否") val = "0";
        return val;
    }
});

//处理百分比
jQuery.extend($.fn.fmatter, {
    percentFmatter: function (cellvalue, options, rowdata) {
        if (typeof (cellvalue) == "undefined" || cellvalue == null) {
            cellvalue = 0;
        }
        var newVal = Math.round(cellvalue * 1000000) / 10000;
        return newVal + "%";
    }
});
jQuery.extend($.fn.fmatter.percentFmatter, {
    unformat: function (cellvalue, options) {
        var val = cellvalue.replace("%", "");
        return parseFloat((parseFloat(val) / 100).toFixed(6));
    }
});


//处理整数
jQuery.extend($.fn.fmatter, {
    intFmatter: function (cellvalue, options, rowdata) {
        if (typeof (cellvalue) == "undefined" || cellvalue == null) {
            cellvalue = 0;
        }
        if (isNaN(cellvalue) || $.trim(cellvalue) == '') cellvalue = 0;
        cellvalue=Math.round(cellvalue);
        return cellvalue;
    }
});
jQuery.extend($.fn.fmatter.intFmatter, {
    unformat: function (cellvalue, options) {
        return cellvalue;
    }
});

//长字符串，用省略号代替显示
//处理整数
jQuery.extend($.fn.fmatter, {
    StringFmatter: function (cellvalue, options, rowdata) {
        
        if (typeof (cellvalue) == "undefined" || cellvalue == null ) {
            cellvalue = "";
        }
        if (cellvalue.length > 20)
            cellvalue = cellvalue.substring(0,20) + "...";
        return cellvalue;
    }
});
jQuery.extend($.fn.fmatter.StringFmatter, {
    unformat: function (cellvalue, options) {
        return cellvalue;
    }
});

//绝对值 负数显示红字
jQuery.extend($.fn.fmatter, {
    snNumber: function (cellvalue, options, rowdata) {
        if (typeof (cellvalue) == "undefined" || cellvalue == null) {
            cellvalue = 0;
        }
        if (isNaN(cellvalue) || $.trim(cellvalue) == '') cellvalue = 0;
        cellvalue = parseFloat(cellvalue);
        var defRealDecimalPlaces = 2;
        if (typeof (options.colModel.formatoptions) != 'undefined') {
            if (typeof (options.colModel.formatoptions.realDecimalPlaces) == 'number') {
                defRealDecimalPlaces = options.colModel.formatoptions.realDecimalPlaces;
            }
            else if (typeof (options.colModel.formatoptions.realDecimalPlaces) == 'function') {
                defRealDecimalPlaces = options.colModel.formatoptions.realDecimalPlaces();
            }
        }
        //var realValue = Math.round(cellvalue * Math.pow(10, defRealDecimalPlaces)) / Math.pow(10, defRealDecimalPlaces);
        var cellvalue = Math.round(cellvalue * Math.pow(10, defRealDecimalPlaces)) / Math.pow(10, defRealDecimalPlaces);

        if (cellvalue < 0) {
            cellvalue = '<font color="red">' + formatNumber(cellvalue, defRealDecimalPlaces) + '</font>';
        }
        else { cellvalue = formatNumber(cellvalue, defRealDecimalPlaces); }
        //if (defRealDecimalPlaces != 2) { cellvalue += "<span  style='display:none'>\"" + realValue + "\"</span>"; }
        return cellvalue;
    }
});
jQuery.extend($.fn.fmatter.snNumber, {
    unformat: function (cellvalue, options) {
        cellvalue = cellvalue.replace(/,/ig, ''); //替换,号
        return parseFloat(cellvalue);
    }
});

jQuery.extend({
    funGetOptions: function (id) {
        //var html = "'':请选择;"
        var html = "";
        var json = selectListItems[id];
        if (typeof (json) != "undefined" && json != null) {
            for (var i = 0; i < json.length; i++) {
                html = html + json[i]['value'] + ":" + json[i]['text'] + ";";
            }
        }
        return html.substring(0, html.length - 1);
    }
});
//处理下拉菜单
jQuery.extend($.fn.fmatter, {
    getValue: function (cellvalue, options, rowdata) {
        var val = "";
        if ((typeof (cellvalue) == "undefined") || cellvalue == null) val = "";
        else {
            try {
                var json = selectListItems[options.colModel.formatoptions.id];
                for (var i = 0; i < json.length; i++) {
                    if (json[i]['value'] == cellvalue)
                        val = json[i]['text'];
                }

            } catch (e) {
                alert(e);
                val = "";
            }
        }
        return val;
    },
    selectView: function (cellvalue, options, rowdata) {
        var html = "";
        var selected;
        if ((typeof (cellvalue) == "undefined") || cellvalue == null) html = "";
        else {
            try {
                html = "<select id=" + options.colModel.formatoptions.name + ">"
                var json = selectListItems[options.colModel.formatoptions.id];
                for (var i = 0; i < json.length; i++) {

                    if (json[i]['value'] == cellvalue)
                        selected = "selected";
                    else
                        selected = "";
                    html = html + "<option value='" + json[i]['value'] + "' selected='" + selected + "' > " + json[i]['text'] + " </option>";

                }
                html = html + "</select>";

            } catch (e) {
                alert(e); html = "";
            }
        }
        return html;
    }
});

//单元格自动跳转 2012-2-9 李保庆
jQuery.extend({
    goToNextCell: function (grid, iRow, iCol, addRowEvent) {
        if (event == undefined || event.keyCode != 13) return;
        var colModels = $(grid).getGridParam('colModel');
        addRowEvent = false; //屏蔽自动加行
        if (iCol >= colModels.length - 1) {
            if (iCol == colModels.length - 1) {
                //最后一列
                if (iRow == $(grid).getRowData().length) {
                    //最后一行,直接添加一行
                    if (typeof (addRowEvent) == 'function') {
                        addRowEvent();
                    }
                    else {
                        if (typeof (addRowEvent) == 'boolean' && !addRowEvent) {
                            return;
                        }
                        var data = {};
                        $(grid).addRowData(iRow + 1, data);
                    }
                }
                //定位到下一行的第一列上
                $.goToNextCell(grid, iRow + 1, 0, addRowEvent);
            }
            return;
        }
        var colModel = colModels[iCol + 1];
        if (colModel.editable == true && !colModel.hidden && (colModel.autofocus == undefined || colModel.autofocus)) {
            setTimeout(function () {
                $(grid).editCell(iRow, iCol + 1, true);
                var inputE = $(grid).find("td[class='edit-cell ui-state-highlight']").find("input[type='text']");
                try {
                    inputE.focus();
                    inputE.select();
                } catch (e) { }
                if (iCol < 3) {
                    //将滚动条滚到第一列
                    $("#gview_" + grid.replace('#', '') + " .ui-jqgrid-bdiv").scrollLeft(-9999)
                }
                else if (iCol > 8) {
                    $("#gview_" + grid.replace('#', '') + " .ui-jqgrid-bdiv").scrollLeft(9999)
                }
                return iRow;
            }, 2);
        }
        else {
            $.goToNextCell(grid, iRow, iCol + 1, addRowEvent);
        }
    }
});
//单元格自动选择  2012-2-9 李保庆
jQuery.extend({
    autoSelectCell: function (rowid, cellname, value) {
        //debugger;
        var inputId = "#" + rowid + "_" + cellname;
        var type = $(inputId).attr("type");
        if (type === "text") {
            if ($(inputId).attr("__type") == "date") {

            }
            setTimeout(function () {
                try {
                    $(inputId)[0].focus();
                    $(inputId)[0].select();
                } catch (e) {
                }
            }, 0);
        }
    }
});
